from PySide6.QtWidgets import QMainWindow, QLabel, QLineEdit, QCheckBox, \
    QPushButton, QGroupBox, QMessageBox
from PySide6 import QtCore
import os
import sys
import json
import myUtils


class ConfigWindow(QMainWindow):
    def __init__(self, main):
        super().__init__()
        self.main = main
        self.setWindowTitle('设置')
        self.setFixedSize(240, 400)
        home_dir = os.path.expanduser("~")
        config_path = home_dir + "\\AppData\\Local\\Moyu\\config.json"
        self.config_path = config_path
        if os.path.exists(config_path):
            print('文件存在')
            f = open(config_path, 'r')
            param_dict = json.loads(f.read())
            f.close()
        else:
            print('文件不存在')
            return

        self.l1 = QLabel(self)
        self.l1.setText("计薪天数")
        self.l1.setGeometry(QtCore.QRect(10, 12, 64, 20))
        self.e1 = QLineEdit(self)
        self.e1.setText(param_dict['working_days'])
        self.e1.setGeometry(QtCore.QRect(80, 10, 100, 24))

        self.l2 = QLabel(self)
        self.l2.setText("上班区间")
        self.l2.setGeometry(QtCore.QRect(10, 42, 64, 20))
        self.e2 = QLineEdit(self)
        self.e2.setText(param_dict['working_hours'])
        self.e2.setGeometry(QtCore.QRect(80, 40, 100, 24))

        self.l3 = QLabel(self)
        self.l3.setText("月薪")
        self.l3.setGeometry(QtCore.QRect(10, 72, 64, 20))
        self.e3 = QLineEdit(self)
        self.e3.setText(param_dict['monthly_pay'])
        self.e3.setGeometry(QtCore.QRect(80, 70, 100, 24))

        self.l4 = QLabel(self)
        self.l4.setText("刷新间隔(s)")
        self.l4.setGeometry(QtCore.QRect(10, 102, 64, 20))
        self.e4 = QLineEdit(self)
        self.e4.setText(param_dict['refresh_interval_seconds'])
        self.e4.setGeometry(QtCore.QRect(80, 100, 100, 24))

        self.l5 = QLabel(self)
        self.l5.setText("开机自动启动")
        self.l5.setGeometry(QtCore.QRect(10, 130, 88, 20))
        self.cb1 = QCheckBox("", self)
        self.cb1.setGeometry(QtCore.QRect(100, 130, 100, 20))
        self.cb1.setCheckState(QtCore.Qt.CheckState.Checked if is_autostart() else QtCore.Qt.CheckState.Unchecked)

        self.l6 = QLabel(self)
        self.l6.setText("显示 剩余时间")
        self.l6.setGeometry(QtCore.QRect(10, 150, 88, 20))
        self.cb2 = QCheckBox("", self)
        self.cb2.setGeometry(QtCore.QRect(100, 150, 100, 20))
        self.cb2.setCheckState(
            QtCore.Qt.CheckState.Checked if param_dict['is_show_remaining_time'] == "1" else QtCore.Qt.CheckState.Unchecked)

        self.b1 = QPushButton("应用", self)
        self.b1.setGeometry(QtCore.QRect(56, 180, 128, 30))
        self.b1.clicked.connect(self.yingyong)

        self.groupBox = QGroupBox("一览", self)
        self.groupBox.setGeometry(QtCore.QRect(10, 240, 218, 128))
        self.l8 = QLabel(self.groupBox)

        s1 = float(param_dict['monthly_pay'])  # 月薪
        s2 = float(param_dict['working_days'])  # 计薪天数
        secondsUnitPrice = s1 / s2 / myUtils.getWorkingHours(param_dict['working_hours']) / 60 / 60
        self.l8.setText("每天工时：" + str(myUtils.getWorkingHours(param_dict['working_hours'])) + "时\n平均每天：" + (
                "%.6f" % (secondsUnitPrice * 3600 * myUtils.getWorkingHours(
            param_dict['working_hours']))) + "\n平均每小时：" + (
                                "%.6f" % (secondsUnitPrice * 3600)) + "\n平均每分钟：" + (
                                "%.6f" % (secondsUnitPrice * 60)) + "\n平均每秒：" + (
                                "%.6f" % secondsUnitPrice) + "\n")
        self.l8.setGeometry(QtCore.QRect(18, 18, 200, 110))


    def yingyong(self):
        try:
            s1 = float(self.e3.text())  # 月薪
            s2 = float(self.e1.text())  # 计薪天数
            secondsUnitPrice = s1 / s2 / myUtils.getWorkingHours(self.e2.text()) / 60 / 60
            self.l8.setText("每天工时：" + str(myUtils.getWorkingHours(self.e2.text())) + "时\n平均每天：" + ("%.6f" % (
                    secondsUnitPrice * 3600 * myUtils.getWorkingHours(self.e2.text()))) + "\n平均每小时：" + (
                                    "%.6f" % (secondsUnitPrice * 3600)) + "\n平均每分钟：" + (
                                    "%.6f" % (secondsUnitPrice * 60)) + "\n平均每秒：" + (
                                    "%.6f" % secondsUnitPrice) + "\n")
        except BaseException:
            print("BaseException")
            QMessageBox.critical(
                self,
                "错误",
                "应用的参数格式不合法。",
                QMessageBox.StandardButton.Close,
                QMessageBox.StandardButton.Close
            )
            return

        # 更新开机启动
        if self.cb1.checkState().value == 2:
            set_autostart()
        else:
            remove_autostart()

        # print('更新配置文件')
        param_dict = {"working_days": self.e1.text(), "working_hours": self.e2.text(), "monthly_pay": self.e3.text(),
                      "refresh_interval_seconds": self.e4.text(),
                      "is_show_remaining_time": "1" if self.cb2.checkState().value == 2 else "0"}
        param_json = json.dumps(param_dict, sort_keys=False, indent=4, separators=(",", ": "))
        f = open(self.config_path, "w")
        f.write(param_json)
        f.close()
        self.main.yingyong()


# 检查是否开机启动
def is_autostart():
    settings = QtCore.QSettings(r"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
                                QtCore.QSettings.Format.NativeFormat)
    if settings.value("Moyu") == sys.argv[0].replace("/", "\\"):
        return True
    else:
        return False


# 设置开机自启动
def set_autostart():
    settings = QtCore.QSettings(r"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
                                QtCore.QSettings.Format.NativeFormat)
    settings.setValue("Moyu", sys.argv[0].replace("/", "\\"))


# 移除开机自启动
def remove_autostart():
    settings = QtCore.QSettings(r"HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
                                QtCore.QSettings.Format.NativeFormat)
    settings.remove("Moyu")
